using System.IO;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using Microsoft.Win32;

namespace LicenseApp.Client.Controls;

/// <summary>
/// 客户端集成专用的授权管理控件
/// 简化版本，不包含监控控制功能
/// </summary>
public partial class LicenseManagementControl : UserControl
{
    /// <summary>
    /// 状态变化事件
    /// </summary>
    public event Action<LicenseStatusInfo>? StatusChanged;

    /// <summary>
    /// 是否自动刷新状态显示
    /// </summary>
    public bool AutoRefreshStatus { get; set; } = true;

    public LicenseManagementControl()
    {
        InitializeComponent();
        InitializeControl();
    }

    private void InitializeControl()
    {
        // 检查公钥状态
        CheckPublicKeyStatus();

        // 初始化机器码显示
        InitializeMachineCode();

        // 检查是否已有授权
        RefreshStatus();

        // 注意：监控应该由主应用程序通过 LicenseManager.StartLicenseMonitoring() 启动
        // 这里只负责UI显示，不负责启动监控
    }

    private void CheckPublicKeyStatus()
    {
        try
        {
            // 应用程序路径获取 - 按要求实现
            string assemblyFilePath = System.Diagnostics.Process.GetCurrentProcess().MainModule?.FileName ?? "";
            string assemblyDirPath = System.IO.Path.GetDirectoryName(assemblyFilePath) ?? "";
            string publicKeyPath = System.IO.Path.Combine(assemblyDirPath, "public.xml");

            if (System.IO.File.Exists(publicKeyPath))
            {
                var publicKeyContent = System.IO.File.ReadAllText(publicKeyPath);

                // 验证公钥格式
                if (IsValidPublicKey(publicKeyContent))
                {
                    txtPublicKeyStatus.Text = "✅ 已导入";
                    txtPublicKeyStatus.Foreground = Brushes.Green;
                    txtPublicKeyInfo.Text = $"公钥文件: {publicKeyPath}\n文件大小: {new System.IO.FileInfo(publicKeyPath).Length} 字节";

                    // 初始化授权系统
                    LicenseManager.Initialize(publicKeyContent);
                }
                else
                {
                    txtPublicKeyStatus.Text = "❌ 格式错误";
                    txtPublicKeyStatus.Foreground = Brushes.Red;
                    txtPublicKeyInfo.Text = "公钥文件格式不正确，请重新导入";
                }
            }
            else
            {
                txtPublicKeyStatus.Text = "❌ 未导入";
                txtPublicKeyStatus.Foreground = Brushes.Red;
                txtPublicKeyInfo.Text = $"请导入公钥文件到: {publicKeyPath}";
            }
        }
        catch (Exception ex)
        {
            txtPublicKeyStatus.Text = "❌ 检查失败";
            txtPublicKeyStatus.Foreground = Brushes.Red;
            txtPublicKeyInfo.Text = $"检查公钥状态时发生错误: {ex.Message}";
        }
    }

    private bool IsValidPublicKey(string publicKeyContent)
    {
        try
        {
            return !string.IsNullOrWhiteSpace(publicKeyContent) &&
                   publicKeyContent.Contains("<RSAKeyValue>") &&
                   publicKeyContent.Contains("</RSAKeyValue>");
        }
        catch
        {
            return false;
        }
    }

    private void RefreshStatus()
    {
        try
        {
            var statusInfo = LicenseManager.GetCurrentStatus();

            // 更新状态指示器
            UpdateStatusIndicator(statusInfo.Status);

            // 更新状态文本
            txtStatus.Text = GetStatusText(statusInfo.Status);

            // 更新详细信息
            UpdateStatusDetails(statusInfo);

            // 更新状态栏
            var licenseInfo = LicenseManager.GetLicenseInfo();
            if (licenseInfo != null)
            {
                txtStatusBar.Text = $"授权状态: {GetStatusText(statusInfo.Status)} | AGV: {licenseInfo.AgvCount}台 | 最后检查: {DateTime.Now:HH:mm:ss}";
            }
            else
            {
                txtStatusBar.Text = $"状态: {GetStatusText(statusInfo.Status)} | 最后检查: {DateTime.Now:HH:mm:ss}";
            }

            // 触发状态变化事件
            StatusChanged?.Invoke(statusInfo);
        }
        catch (Exception ex)
        {
            txtStatus.Text = "检查失败";
            statusIndicator.Fill = Brushes.Red;
            txtStatusBar.Text = $"状态检查失败: {ex.Message}";
        }
    }

    private void UpdateStatusIndicator(LicenseStatus status)
    {
        statusIndicator.Fill = status switch
        {
            LicenseStatus.Valid => Brushes.Green,
            LicenseStatus.ExpiringSoon => Brushes.Orange,
            LicenseStatus.ExpiredGracePeriod => Brushes.Red,
            LicenseStatus.Expired => Brushes.Red,
            _ => Brushes.Gray
        };
    }

    private string GetStatusText(LicenseStatus status)
    {
        return status switch
        {
            LicenseStatus.Valid => "有效",
            LicenseStatus.ExpiringSoon => "即将到期",
            LicenseStatus.ExpiredGracePeriod => "已过期(宽限期)",
            LicenseStatus.Expired => "已过期",
            _ => "未知"
        };
    }

    private void UpdateStatusDetails(LicenseStatusInfo statusInfo)
    {
        try
        {
            // 获取授权信息
            var licenseInfo = LicenseManager.GetLicenseInfo();

            if (licenseInfo != null)
            {
                // 更新基本信息
                txtStartDate.Text = licenseInfo.StartDate.ToString("yyyy-MM-dd");
                txtEndDate.Text = licenseInfo.EndDate.ToString("yyyy-MM-dd");
                txtDays.Text = $"{licenseInfo.Days} 天";
                txtAgvCount.Text = $"{licenseInfo.AgvCount} 台";
            }
            else
            {
                // 清空信息
                txtStartDate.Text = "-";
                txtEndDate.Text = "-";
                txtDays.Text = "-";
                txtAgvCount.Text = "-";
            }

            // 更新状态消息
            var statusMessage = new StringBuilder();
            statusMessage.Append(statusInfo.Message);

            if (statusInfo.RemainingDays >= 0)
            {
                statusMessage.Append($" (剩余 {statusInfo.RemainingDays} 天)");
            }

            txtStatusMessage.Text = statusMessage.ToString();
            txtLastCheckTime.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        }
        catch (Exception ex)
        {
            txtStatusMessage.Text = $"获取详细信息失败: {ex.Message}";
            txtLastCheckTime.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        }
    }

    /// <summary>
    /// 外部状态变化通知（由主应用程序调用）
    /// </summary>
    /// <param name="statusInfo">状态信息</param>
    public void OnExternalStatusChanged(LicenseStatusInfo statusInfo)
    {
        Dispatcher.BeginInvoke(() =>
        {
            // 更新界面状态
            UpdateStatusIndicator(statusInfo.Status);
            txtStatus.Text = GetStatusText(statusInfo.Status);
            UpdateStatusDetails(statusInfo);

            // 触发状态变化事件
            StatusChanged?.Invoke(statusInfo);
        });
    }

    private void BtnImportPublicKey_Click(object sender, RoutedEventArgs e)
    {
        var openFileDialog = new OpenFileDialog
        {
            Title = "选择公钥文件",
            Filter = "XML文件 (*.xml)|*.xml|所有文件 (*.*)|*.*",
            DefaultExt = "xml"
        };

        if (openFileDialog.ShowDialog() != true)
            return;

        try
        {
            var sourceFile = openFileDialog.FileName;
            var publicKeyContent = System.IO.File.ReadAllText(sourceFile);

            // 验证公钥格式
            if (!IsValidPublicKey(publicKeyContent))
            {
                MessageBox.Show("选择的文件不是有效的RSA公钥文件", "格式错误",
                    MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            // 应用程序路径获取 - 按要求实现
            string assemblyFilePath = System.Diagnostics.Process.GetCurrentProcess().MainModule?.FileName ?? "";
            string assemblyDirPath = System.IO.Path.GetDirectoryName(assemblyFilePath) ?? "";
            string targetPath = System.IO.Path.Combine(assemblyDirPath, "public.xml");

            // 复制文件
            System.IO.File.Copy(sourceFile, targetPath, true);

            // 初始化授权系统
            bool initResult = LicenseManager.Initialize(publicKeyContent);

            if (initResult)
            {
                LicenseManager.ShowNotification("公钥导入成功", LicenseStatus.Valid);

                // 刷新公钥状态
                CheckPublicKeyStatus();

                // 刷新授权状态
                RefreshStatus();
            }
            else
            {
                MessageBox.Show("公钥导入失败，初始化授权系统时出错", "错误",
                    MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show($"导入公钥时发生错误: {ex.Message}", "错误",
                MessageBoxButton.OK, MessageBoxImage.Error);
        }
    }

    private void BtnRegister_Click(object sender, RoutedEventArgs e)
    {
        var licenseCode = txtLicenseCode.Text.Trim();

        if (string.IsNullOrEmpty(licenseCode))
        {
            MessageBox.Show("请输入授权码", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
            return;
        }

        // 检查公钥状态
        if (txtPublicKeyStatus.Text.Contains("未导入") || txtPublicKeyStatus.Text.Contains("格式错误"))
        {
            var result = MessageBox.Show("尚未导入有效的公钥文件，无法验证授权码。\n\n是否现在导入公钥？",
                "需要公钥", MessageBoxButton.YesNo, MessageBoxImage.Question);

            if (result == MessageBoxResult.Yes)
            {
                BtnImportPublicKey_Click(sender, e);
                return;
            }
            else
            {
                return;
            }
        }

        try
        {
            // 注册授权码
            bool success = LicenseManager.RegisterLicense(licenseCode);

            if (success)
            {
                LicenseManager.ShowNotification("授权码注册成功", LicenseStatus.Valid);

                // 清空输入框
                txtLicenseCode.Clear();

                // 刷新状态
                RefreshStatus();
            }
            else
            {
                var errorMsg = "授权码注册失败，可能的原因：\n" +
                              "1. 授权码格式不正确\n" +
                              "2. 授权码签名验证失败\n" +
                              "3. 公钥与授权码不匹配\n\n" +
                              "请确认授权码和公钥是配套的。";

                MessageBox.Show(errorMsg, "注册失败", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show($"注册过程中发生错误: {ex.Message}", "错误",
                MessageBoxButton.OK, MessageBoxImage.Error);
        }
    }

    private void BtnRefreshStatus_Click(object sender, RoutedEventArgs e)
    {
        RefreshStatus();
    }

    private void BtnCheckStatus_Click(object sender, RoutedEventArgs e)
    {
        RefreshStatus();
    }

    /// <summary>
    /// 公开方法：刷新状态
    /// </summary>
    public void RefreshLicenseStatus()
    {
        RefreshStatus();
    }

    /// <summary>
    /// 公开方法：获取当前授权状态
    /// </summary>
    public LicenseStatusInfo GetCurrentStatus()
    {
        return LicenseManager.GetCurrentStatus();
    }

    /// <summary>
    /// 公开方法：获取授权信息
    /// </summary>
    public LicenseInfo? GetLicenseInfo()
    {
        return LicenseManager.GetLicenseInfo();
    }

    #region 机器码相关功能

    /// <summary>
    /// 初始化机器码显示
    /// </summary>
    private void InitializeMachineCode()
    {
        try
        {
            RefreshMachineCode();
        }
        catch (Exception ex)
        {
            txtMachineCode.Text = "获取失败";
            txtMachineCode.ToolTip = $"获取机器码失败: {ex.Message}";
        }
    }

    /// <summary>
    /// 刷新机器码显示
    /// </summary>
    private void RefreshMachineCode()
    {
        try
        {
            var machineCode = MachineCodeGenerator.GenerateMachineCode();
            txtMachineCode.Text = machineCode;
            txtMachineCode.ToolTip = $"机器码: {machineCode}\n生成时间: {DateTime.Now:yyyy-MM-dd HH:mm:ss}\n\n将此机器码发送给供应商以获取绑定授权码";
        }
        catch (Exception ex)
        {
            txtMachineCode.Text = "获取失败";
            txtMachineCode.ToolTip = $"获取机器码失败: {ex.Message}";
        }
    }

    /// <summary>
    /// 复制机器码按钮点击事件
    /// </summary>
    private void BtnCopyMachineCode_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            if (!string.IsNullOrEmpty(txtMachineCode.Text) && txtMachineCode.Text != "获取失败")
            {
                Clipboard.SetText(txtMachineCode.Text);
                MessageBox.Show($"机器码已复制到剪贴板！\n\n机器码: {txtMachineCode.Text}\n\n请将此机器码发送给供应商，以获取绑定到当前机器的授权码。",
                              "复制成功", MessageBoxButton.OK, MessageBoxImage.Information);
            }
            else
            {
                MessageBox.Show("没有可复制的机器码", "提示",
                              MessageBoxButton.OK, MessageBoxImage.Warning);
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show($"复制机器码失败: {ex.Message}", "错误",
                          MessageBoxButton.OK, MessageBoxImage.Error);
        }
    }

    /// <summary>
    /// 刷新机器码按钮点击事件
    /// </summary>
    private void BtnRefreshMachineCode_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            RefreshMachineCode();
            MessageBox.Show("机器码已刷新", "提示",
                          MessageBoxButton.OK, MessageBoxImage.Information);
        }
        catch (Exception ex)
        {
            MessageBox.Show($"刷新机器码失败: {ex.Message}", "错误",
                          MessageBoxButton.OK, MessageBoxImage.Error);
        }
    }

    /// <summary>
    /// 机器码详细信息按钮点击事件
    /// </summary>
    private void BtnMachineCodeDetails_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            var details = MachineCodeGenerator.GetMachineCodeComponents();
            MessageBox.Show(details, "机器码详细信息",
                          MessageBoxButton.OK, MessageBoxImage.Information);
        }
        catch (Exception ex)
        {
            MessageBox.Show($"获取机器码详细信息失败: {ex.Message}", "错误",
                          MessageBoxButton.OK, MessageBoxImage.Error);
        }
    }

    /// <summary>
    /// 公开方法：获取当前机器码
    /// </summary>
    public string GetMachineCode()
    {
        try
        {
            return MachineCodeGenerator.GenerateMachineCode();
        }
        catch
        {
            return "";
        }
    }

    #endregion
}
